package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        // 判断是否是套餐，如果是套餐，就把审核状态设置为初始化
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else{
            // 如果不是套餐无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        // 无论是不是套餐，不能设置上架销售状态
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        // 判断是否已经上架
        ServiceItem oldObj = this.get(serviceItem.getId());
        // 表示已经上架了，不能修改
        if (ServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())){
            throw new BusinessException("服务单项处于上架状态，不允许进行修改");
        }
        // 表示不是上架状态，但是处于审核状态不能进行修改
        if (ServiceItem.AUDITSTATUS_AUDITING.equals(oldObj.getAuditStatus()) && ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage())){
            throw new BusinessException("服务单项处于审核状态，不允许进行修改");
        }
        // 表示不是上架状态，但是处于审核通过状态，需要重新审核
        if (ServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus()) && ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else {
            // 表示不是上架状态，设置为原来的状态
            serviceItem.setAuditStatus(oldObj.getAuditStatus());
        }
        // 销售状态 ====> 设置为下架，因为修改过之后要重新上架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        // 把套餐设置回去，防止变成null
        // serviceItem.setCarPackage(oldObj.getCarPackage());
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        // 判断销售状态
        // 表示上架状态
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            throw new BusinessException("服务项处于上架状态！");
        }
        // 如果是套餐要先审核，再进行上架
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) && !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){
            throw new BusinessException("套装审核通过才能上架");
        }
        // 如果不是套餐就无需审核
        // 把销售状态设置为上架
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        // 进行合理化检验
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus()) // 处于上架状态
        || ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage()) // 不是套餐
        || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) // 审核中
        || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()) // 审核通过
        || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus()) // 无需审核
        ){
            throw new BusinessException("非法操作");
        }
        // 创建套餐审核对象
        CarPackageAudit audit = new CarPackageAudit();
        audit.setCreateTime(new Date()); // 创建时间
        audit.setAuditorId(director); // 审核人
        audit.setBpmnInfoId(bpmnInfoId); // 流程定id
        audit.setCreator(ShiroUtils.getUser().getUserName()); // 创建人当前登录用户
        audit.setInfo(info); // 备注信息
        audit.setServiceItemId(serviceItem.getId()); // 服务单项id
        audit.setServiceItemName(serviceItem.getName()); // 服务单项名称
        audit.setServiceItemPrice(serviceItem.getDiscountPrice()); // 服务单项价格
        audit.setServiceItemInfo(serviceItem.getInfo()); // 服务单项备注信息
        // 往数据库中添加数据
        carPackageAuditService.save(audit);
        // 获取流程定义对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        // 指定负责人
        Map<String, Object> params = new HashMap<>();
        params.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        params.put("director",director);
        if (finance != null){
            params.put("finance",finance);
        }
        // 启动流程
        ProcessInstance processInstance = runtimeService.
                startProcessInstanceByKey(bpmnInfo.getActProcessKey(), String.valueOf(audit.getId()), params);
        // 启动流程的目的就是为了获取流程实例的id
        audit.setInstanceId(processInstance.getId());
        // 由于上面添加的对象的流程实例id是null，所以要修改对象
        carPackageAuditService.update(audit);
        // 把服务单项的状态修改为审核中
        serviceItemMapper.changeAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING);
    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId,status);
    }
}
